'''
    FogBugz Abstraction to facilitate the posting and editing of new cases
    through interfaces that are not FogBugz. Oh and please, let the tests
    drive any changes to this class. If you don't a man will come to you
    in your sleep... I'm not saying what he'll do, just FYI.

    Wayne Witzel III
    Tower Hill Insurance Group
    Copyright 2008
    
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import pycurl as curl
from xml.dom.minidom import parseString

# Start here if you aren't sure.
FOGBUGZ_API_URL = 'http://fogbugz.thig.com/api.php'
FOGBUGZ_RESPONSE_COLS = ['ixBug', 'sTitle']
# Stop here if you aren't sure.

class Response(object):
    def __init__(self):
        self.data = ''

    def callback(self, r):
        self.data = self.data + r

class Request(object):
    def __init__(self, cmd):
        
        self.c = curl.Curl()
        
        self.response = Response()
        self.c.setopt(curl.WRITEFUNCTION,self.response.callback)
        
        self.cmd = cmd
        self.params = {}

    def perform(self):
        # For some reason I can't do q(params[p]) when using
        # string replacement, so we have this for loop instead
        # of the obfuscated list comprehension I was gonna use.
        #
        self.params['cmd'] = self.cmd
        query_string = '?cols=' + ','.join(FOGBUGZ_RESPONSE_COLS)
        
        postdata = []
        for k in self.params:
            value = self.params[k]
            if value:
                if type(value) is tuple:
                    postdata.append((k,value))
                else:
                    value = str(value)
                    postdata.append((k, '%s' % value))
            else:
                postdata.append((k, ''))		
        
        self.c.setopt(curl.HTTPPOST, postdata)
        self.c.setopt(curl.URL, FOGBUGZ_API_URL + query_string)
        self.c.perform()
        self.c.close()
        
        fbzdom = parseString(self.response.data)

        # Yeah, it is wrong to just ignore the rest of the
        # values in the node, assuming there is more. Right now, ol' well.
        #
        error_nodes = fbzdom.getElementsByTagName("error")
        if error_nodes.length:
            self.params['error'] = error_nodes[0].childNodes[0].nodeValue
        else:
            self.params['error'] = None
            
        token_nodes = fbzdom.getElementsByTagName("token")
        if token_nodes.length:
            self.params['token'] = token_nodes[0].childNodes[0].nodeValue
            
        for col in FOGBUGZ_RESPONSE_COLS:    
            nodes = fbzdom.getElementsByTagName(col)
            if nodes.length:
                self.params[col] = nodes[0].childNodes[0].nodeValue
                
        return self.params
    
    # The following class methods are just so I can
    # maintain the interface to the Request object if
    # FogBugz decides to change the `logon` action to `login`
    #    
    def logon(cls):
        return cls('logon')
    logon = classmethod(logon)
    
    def logoff(cls):
        return cls('logoff')
    logoff = classmethod(logoff)
    
    def new(cls):
        return cls('new')
    new = classmethod(new)
    
    def edit(cls):
        return cls('edit')
    edit = classmethod(edit)
    
    def search(cls):
        return cls('search')
    search = classmethod(search)
    
class Authentication(object):
    def __init__(self, email, password):
        self.email = email
        self.password = password
        self.valid = None
        
    def logon(self):
        r = Request.logon()
        r.params = self.__dict__
        for k,v in r.perform().items():
            if getattr(self, k) != v:
                setattr(self, k, v)        
        try:
            self.valid = True
            return self.token
        except AttributeError:
            self.valid = False
            return None
        
    def logoff(self):
        r  = Request.logoff()
        r.params = self.__dict__
        for k,v in r.perform().items():
            if getattr(self, k) != v:
                setattr(self, k, v)
        self.valid = False
        
class Case(object):
    def __init__(self, auth, ixBug=None):
        self.token = auth.logon()
        self.ixBug = ixBug
        self.nFileCount = 0
        
        if self.ixBug:
            # load up information from FogBugz
            self.q = self.ixBug
            r = Request.search()
            self._perform(r)
        else:
            pass
    
    def attachFile(self, filename):
        # Making a note here, since this might bite me
        # then I can say I told you so.
        #
        self.nFileCount += 1
        self.__dict__['File%d' % self.nFileCount] = (curl.FORM_FILE, filename)
    
    def save(self):
        if self.ixBug:
            r = Request.edit()
            self._perform(r)
        else:
            r = Request.new()
            self._perform(r)
    
    def _perform(self, request):
        # You think this is safe? I do .. mostly.
        #
        request.params = self.__dict__
        self.__dict__ = request.perform()
